package com.jt.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/findAll")
    public List<User> findAll(){

        return userService.findAll();
    }

    /**
     * JSONP的跨域请求  特殊的格式封装.....
     * 需求分析:校验用户的数据是否可用.
     * url: http://sso.jt.com/user/check/{param}/{type}
     * 参数: param/type
     * 返回值结果: SysResult对象
     */
    @RequestMapping("/check/{param}/{type}")
    public JSONPObject chcekUser(@PathVariable String param,
                                 @PathVariable Integer type,
                                 String callback){
        //根据信息查询数据库获取响应记录
        Boolean flag = userService.checkUser(param,type);
        return new JSONPObject(callback, SysResult.success(flag));
    }

    /**
     * 测试httpClient调用方式
     * url地址: http://sso.jt.com/user/findUserById/"+userId
     * 返回:  user对象的JSON数据
     */
    @RequestMapping("/findUserById/{userId}")
    public User findUserById(@PathVariable Long userId){

        return userService.findUserById(userId);
    }

    /**
     * 根据ticket信息查询用户的json信息 jsonp请求 返回值使用特定的对象封装.
     * url地址:http://sso.jt.com/user/query/ca620491866a42e596b29ee52fc27aff?callback=jsonp1600333068471&_=1600333068521
     */
    @RequestMapping("/query/{ticket}")
    public JSONPObject findUserByTicket(@PathVariable String ticket, HttpServletResponse response,
                                        String callback){
        if(jedisCluster.exists(ticket)){
            //可以正确返回
            String userJSON = jedisCluster.get(ticket);
            return new JSONPObject(callback, SysResult.success(userJSON));
        }else{
            //如果根据ticket查询有误,则应该删除Cookie信息.
            Cookie cookie = new Cookie("JT_TICKET","");
            cookie.setDomain("jt.com");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            return new JSONPObject(callback, SysResult.fail());
        }

    }








}
